using System;
using System.Data;
using MySql.Data.MySqlClient;
using UnityEngine;

public class SqlAccess:MonoBehaviour
{
    public string host = "localhost";
    public string port = "3306";
    public string username="root";
    public string pwd = "test123";
    public string database = "stock_day_data";
    
    private  MySqlConnection dbConnection;
    

    //链接数据库
    public  void Connect()
    {
        //连接数据库
        try {
            string connectionString = string.Format("server = {0};port={1};database = {2};user = {3};password = {4};", host, port, database, username, pwd);
            Debug.Log(connectionString);
            dbConnection = new MySqlConnection(connectionString);
            dbConnection.Open();
            Debug.Log("连接成功！");
        }
        catch (Exception e) {
            throw new Exception("连接失败！" + e.Message.ToString());
        }
    }

    //执行sql语句
    public DataSet ExecuteSQL(string sqlString)
    {
        if (dbConnection.State == ConnectionState.Open) {
            DataSet ds = new DataSet();
            try {
                MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);
                da.Fill(ds);
            }
            catch (Exception ee) {
                throw new Exception("SQL:" + sqlString + "/n" + ee.Message.ToString());
            }
            finally {
            }
            return ds;
        }
        return null;
    }

    //关闭连接
    public void Close()
    {
        if (dbConnection != null) {
            dbConnection.Close();
            dbConnection.Dispose();
            dbConnection = null;
        }
    }
}
